package com.stb.server.url;

/**
 * Builds URL with params and adds a digest
 */
public class URLEncoderImpl implements URLEncoder {
	
	private static final String PARAM_SEPERATOR = "#";
	
	@Override
	public String encode(String url, String... keyValues) {
		StringBuilder urlBuilder = new StringBuilder(url);
		StringBuilder paramsBuilder = new StringBuilder();
		if (keyValues.length > 0) {
			urlBuilder.append(PARAM_SEPERATOR);
			for (String keyValue : keyValues) {
				paramsBuilder.append(keyValue).append("&");
			}
			paramsBuilder.replace(paramsBuilder.length() - 1, paramsBuilder.length(), "");
			String digest = Encrypter.computeHash(paramsBuilder.toString());
			paramsBuilder.append("&digest=").append(digest);
		}
		urlBuilder.append(paramsBuilder);
		return urlBuilder.toString();
	}

	@Override
	public boolean validate(String url) {
		if (url.indexOf(PARAM_SEPERATOR) == -1) {
			// No params
			return true;
		}
		String digest = url.substring(url.indexOf("digest=") + "digest=".length());
		String params = url.substring(url.indexOf(PARAM_SEPERATOR) + 1, url.indexOf("digest=") - 1);
		return digest.equals(Encrypter.computeHash(params));
	}

	@Override
	public String getParam(String paramURL, String paramName) {
		String[] params = paramURL.split("&");
		for (String param : params) {
			String[] keyValue = param.split("=");
			if (keyValue[0].equals(paramName)) {
				return keyValue[1];
			}
		}
		return null;
	}
}
